import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getMenuInfoByPath } from '@/utils/temp'
import cache from '@/plugins/cache'
import { isEmpty } from '@/utils/validate'
import {getToken} from '@/utils/auth'

/* NProgress 配置 */
NProgress.configure(
  {
    easing: 'ease',
    speed: 150,
    showSpinner: false
  }
);

// 设置白名单
const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  NProgress.start()
  const prefix = 'OS'
  if(getToken()) {
    if (to.path == process.env.VUE_APP_LOCK_SCREEN_PATH) {
      /* 判断是否为强制跳转 */
      if (!isEmpty(cache.local.get('os_lock_screen_password'))) {
        document.title = `${prefix} - 锁屏`
        next()
      }
      else {
        next(from)
      }
    }
    else if (from.path == process.env.VUE_APP_LOCK_SCREEN_PATH && !isEmpty(cache.local.get('os_lock_screen_password'))) {
      document.title = `${prefix} - 锁屏`
      next(from)
    }
    else if (!isEmpty(cache.local.get('os_lock_screen_password'))) {
      document.title = `${prefix} - 锁屏`
      next(process.env.VUE_APP_LOCK_SCREEN_PATH)
    }
    else {
      const menuInfo = getMenuInfoByPath(to.path)
      /* 根据路由path先匹配菜单中的信息，找到后提交vuex */
      if (menuInfo) {
        store.dispatch('menu/routerChange', menuInfo)
        if (to.meta.title) {
          document.title = `${prefix} - ${to.meta.title}`
        }
        else {
          document.title = `${prefix} - No Title`
        }
        next()
      } else {
        document.title = `${prefix} - ${to.meta.title}`
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      document.title = `${prefix} - ${to.meta.title}`
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }

  NProgress.done()
})

router.afterEach(() => {
  NProgress.done()
})